package stream;

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.border.EmptyBorder;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class Memo extends JFrame {
	
	static String filename="Untitled";				
	static boolean modifyFlag=false;		// 수정여부, 종료시킬때 수정여부를 알아내서 저장할지 말지 묻기위한 변수.
	String oriStr="";						// 원본 텍스트;
	int oriLength = 0;						// 원본 파일의 길이.
	
	
	private JPanel contentPane;
	private JMenuBar menuBar;
	private JMenu mnFile;
	private JMenuItem mntmLoad;
	private JMenuItem mntmSave;
	private JMenuItem mntmSaveAs;
	private JLabel status;
	private JScrollPane scrollPane;
	private JTextArea result;
	private JMenuItem mntmNewFile;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					Memo frame = new Memo();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the frame.
	 */
	public Memo() {
		setTitle("Filename : " + filename);
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 645, 489);
		setJMenuBar(getMenuBar_1());
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		contentPane.setLayout(new BorderLayout(0, 0));
		setContentPane(contentPane);
		contentPane.add(getStatus(), BorderLayout.SOUTH);
		contentPane.add(getScrollPane(), BorderLayout.CENTER);
	}
	public void newfile() throws Exception {
		
		if(modifyFlag){
			int yn = JOptionPane.showConfirmDialog(null, "변경된 내용이 있습니다. 저장 하시겠습니까?");
			if(yn == JOptionPane.YES_OPTION) save();
			status.setText("Your File is Safely Saved.");		
		}
		status.setText("New File Created.");
		result.setText("");
		filename = "Untitled";
		setTitle("Filename : " + filename);
		oriStr="";
		oriLength=0;
		
		
		
	}
	
	public void load() throws Exception {
		
		int yn=-1;
		
		if(modifyFlag){ // 현재 파일 내용이 수정된 경우
			yn = JOptionPane.showConfirmDialog(null, "파일이 수정되었습니다. 저장 하시겠습니까?");
			if(yn == JOptionPane.YES_OPTION) save();
		}
		
		// 저장된 이후이거나, 파일이 없거나...
		JFileChooser fc = new JFileChooser();
		yn = fc.showOpenDialog(this);		
		if(yn == JFileChooser.APPROVE_OPTION){ // 열기 버튼 클릭시
			File f = fc.getSelectedFile();
			result.append(f.getPath());
			filename = f.getPath();
			setTitle("Filename : " + filename);
			
			FileReader fr = new FileReader(filename);
			BufferedReader br = new BufferedReader(fr);
			
			result.setText("");
			
			while(true){	
				String str = br.readLine(); // 한 줄 단위로 파일을 읽어들인다. char 배열로 1024 개씩 처리하는거보다 빠름.
				if(str == null) break;
				result.append(str + "\n");
			}
			
			br.close();
			fr.close(); // 닫을때는 역순으로.
			
			oriLength = result.getText().length();
			oriStr = result.getText();
			
			result.setCaretPosition(result.getText().length());
			status.setText("Your File Safely Loaded.");
		}
		
	}
	public void save() throws Exception {
		if(filename.equals("Untitled")){ // 파일명이 정해지지 않았을때
			saveAs();
		}
		
		FileWriter fw = new FileWriter(filename);
		BufferedWriter bw = new BufferedWriter(fw);
		
		bw.write(result.getText());
		status.setText("Your File Safely Saved.");
		bw.close();
		fw.close();
		setTitle("Filename : " + filename);
		
	}
	public void saveAs() throws Exception {
			
	}
	

	private JMenuBar getMenuBar_1() {
		if (menuBar == null) {
			menuBar = new JMenuBar();
			menuBar.add(getMnFile());
		}
		return menuBar;
	}
	private JMenu getMnFile() {
		if (mnFile == null) {
			mnFile = new JMenu("File");
			mnFile.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {					
				}
			});
			mnFile.add(getMntmNewFile());
			mnFile.add(getMntmLoad());
			mnFile.add(getMntmSave());
			mnFile.add(getMntmSaveAs());
		}
		return mnFile;
	}
	private JMenuItem getMntmNewFile() {
		if (mntmNewFile == null) {
			mntmNewFile = new JMenuItem("New File");
			mntmNewFile.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					try{
						newfile();
					}catch(Exception ex){
						status.setText(ex.toString());
					}					
				}
			});
		}
		return mntmNewFile;
	}
	private JMenuItem getMntmLoad() {
		if (mntmLoad == null) {
			mntmLoad = new JMenuItem("Load");
			mntmLoad.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					
					try{
						load();
					}catch(Exception ex){
						status.setText(ex.toString());
					}
					
				}
			});
		}
		return mntmLoad;
	}
	private JMenuItem getMntmSave() {
		if (mntmSave == null) {
			mntmSave = new JMenuItem("Save");
			mntmSave.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {					
					try{
						save();
					}catch(Exception ex){
						status.setText(ex.toString());
					}
				}
			});
		}
		return mntmSave;
	}
	private JMenuItem getMntmSaveAs() {
		if (mntmSaveAs == null) {
			mntmSaveAs = new JMenuItem("Save As");
			mntmSaveAs.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {					
					try{
						saveAs();
					}catch(Exception ex){
						status.setText(ex.toString());
					}
				}
			});
		}
		return mntmSaveAs;
	}
	private JLabel getStatus() {
		if (status == null) {
			status = new JLabel("");
		}
		return status;
	}
	private JScrollPane getScrollPane() {
		if (scrollPane == null) {
			scrollPane = new JScrollPane();
			scrollPane.setViewportView(getResult());
		}
		return scrollPane;
	}
	private JTextArea getResult() {
		if (result == null) {
			result = new JTextArea();
			result.addKeyListener(new KeyAdapter() {
				@Override
				public void keyReleased(KeyEvent ev) {
					status.setText(" Char : " + ev.getKeyChar() + ", Code : " + ev.getKeyCode());
					if(!modifyFlag){
						if(result.getText().length() != oriLength) modifyFlag = true;
						if(!result.getText().equals(oriStr)){
							modifyFlag = true;
							oriStr = null;
						}
					}
					if(modifyFlag){
						setTitle("filename : " + filename + "( *)");
					}
					
					
					
				}
			});
		}
		return result;
	}
	
}
